package cn.demoncat.util.pay.alipay.config;

import java.io.FileInputStream;

import javax.annotation.Resource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;

import cn.demoncat.util.exception.BizErrorRuntimeException;
import cn.demoncat.util.io.CloseUtil;
import cn.demoncat.util.io.IoUtil;
import cn.demoncat.util.lang.constant.StatusConstant.Common;
import cn.demoncat.util.pay.alipay.constant.AlipayConstant;

/**
 * 支付宝配置
 * 
 * @author 延晓磊
 *
 * @since 2017年9月15日
 */
@Configuration
public class AlipayConfig {
	
	@Resource
	private AlipayProperties alipayProperties;

	/**
	 * 支付宝客户端（证书模式）
	 * 
	 * @return
	 * 
	 * @author 延晓磊
	 *
	 * @since 2019年9月24日
	 */
	@Bean
	public AlipayClient alipayClient() {
		// 证书模式
		CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
		// 支付宝网关地址
		certAlipayRequest.setServerUrl(Common.YES.equals(alipayProperties.getStatus()) ? AlipayConstant.SERVER_URL : AlipayConstant.SERVER_URL_DEV);
		// 应用Id
		certAlipayRequest.setAppId(alipayProperties.getAppid());
		// 应用私钥
		FileInputStream pk = null;
		try {
			pk = new FileInputStream(alipayProperties.getPrivateKeyPath());
			certAlipayRequest.setPrivateKey(IoUtil.readToStr(pk).trim());
		} catch (Exception e) {
			throw new BizErrorRuntimeException("创建支付宝客户端失败：请设置正确的支付宝应用私钥文件路径", e);
		}finally {
			CloseUtil.close(pk);
		}
		// 请求格式
		certAlipayRequest.setFormat(AlipayConstants.FORMAT_JSON);
		// 字符集
		certAlipayRequest.setCharset(AlipayConstants.CHARSET_UTF8);
		// 签名类型
		certAlipayRequest.setSignType(AlipayConstants.SIGN_TYPE_RSA2);
		// 应用公钥证书路径
		certAlipayRequest.setCertPath(alipayProperties.getAppCertPath());
		// 支付宝公钥证书路径
		certAlipayRequest.setAlipayPublicCertPath(alipayProperties.getAlipayCertPath());
		// 支付宝根证书路径
		certAlipayRequest.setRootCertPath(alipayProperties.getAlipayRootCertPath());
		// 构造client
		try {
			return new DefaultAlipayClient(certAlipayRequest);
		} catch (AlipayApiException e) {
			throw new BizErrorRuntimeException("创建支付宝客户端失败：" + e.getErrMsg(), e);
		}
	}
 
}
